<<<<<<< HEAD
#coding:utf-8

from flask import Flask,request,make_response
import hashlib
import xml.etree.ElementTree as ET
import requests
from random import randint
from lxml import etree

url='http://www.qiushibaike.com/text'
url2='http://www.qiushibaike.com/text/page/%s/?s=4902718'

app=Flask(__name__)

@app.route('/',methods=['GET','POST'])
def wechat_auth():
    if request.method=='GET':
        print'comingGet'
        data=request.args
        token='在微信公众平台你设置的token'
        signature=data.get('signature','')
        timestamp=data.get('timestamp','')
        nonce=data.get('nonce','')
        echostr=data.get('echostr','')
        s=[timestamp,nonce,token]
        s.sort()
        s=''.join(s)
        if (hashlib.sha1(s).hexdigest()==signature):
            return make_response(echostr)

    if request.method == 'POST':
        xml_str = request.stream.read()
        xml = ET.fromstring(xml_str)
        toUserName = xml.find('ToUserName').text
        fromUserName = xml.find('FromUserName').text
        createTime = xml.find('CreateTime').text
        msgType = xml.find('MsgType').text

        if msgType != 'text':
            reply = '''
            <xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[%s]]></MsgType>
                         <Content><![CDATA[%s]]></Content>
              </xml>
                  '''  % (
                          fromUserName,
                          toUserName,
                          createTime,
                          'text',
                          'Unknown Format, Please check out'
                          )
            return reply

        content = xml.find('Content').text
        msgId = xml.find('MsgId').text
        ###
        if u'笑话' in content or 'joke' in content:
            url = url2 % str(randint(0,30))
            print '\nurl = %s\n' %url
            r = requests.get(url)
            tree = etree.HTML(r.text)
            contentlist = tree.xpath('//div[contains(@id, "qiushi_tag_")]')
            jokes = []

            for i in contentlist:
                content = i.xpath('div[@class="content"]/text()')
                contentstring = ''.join(content)
                contentstring = contentstring.strip('\n')
                jokes.append(contentstring)

            joke = jokes[randint(0,len(jokes))]
            reply = '''
            <xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[%s]]></MsgType>
                         <Content><![CDATA[%s]]></Content>
              </xml>
                  '''  % (
                          fromUserName,
                          toUserName,
                          createTime,
                          msgType,
                          joke 
                          )
            return reply
            
        ###
        else:
            print('type(content)=',type(content))
            if type(content).__name__ == "unicode":
                print('unicode:',content)
                content = content[::-1]
                content = content.encode('UTF-8')
            elif type(content).__name__ == "str":
                print(type(content).__name__)
                print('str: ',content)
		if content.startswith('/::'):
                	content = content.decode('utf-8')
			content = ''.join(['/::'+x for x in content.split('/::') if len(x)>0][::-1])	
		else:
                	content = content.decode('utf-8')
                	content = content[::-1]
        
            reply = '''
            <xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[%s]]></MsgType>
                         <Content><![CDATA[%s]]></Content>
              </xml>
                  '''  % (
                          fromUserName,
                          toUserName,
                          createTime,
                          msgType,
                          content 
                          )
            return reply


if __name__=="__main__":
  while True:
    try:
        app.run(host='0.0.0.0',port=8080)
    except Exception,e:
        print e
=======
#coding:utf-8

from flask import Flask,request,make_response
import hashlib
import xml.etree.ElementTree as ET
import requests
from random import randint
from lxml import etree

url='http://www.qiushibaike.com/text'
url2='http://www.qiushibaike.com/text/page/%s/?s=4902718'

app=Flask(__name__)

@app.route('/',methods=['GET','POST'])
def wechat_auth():
    if request.method=='GET':
        print'comingGet'
        data=request.args
        token='微信公众平台你输入的token'
        signature=data.get('signature','')
        timestamp=data.get('timestamp','')
        nonce=data.get('nonce','')
        echostr=data.get('echostr','')
        s=[timestamp,nonce,token]
        s.sort()
        s=''.join(s)
        if (hashlib.sha1(s).hexdigest()==signature):
            return make_response(echostr)

    if request.method == 'POST':
        xml_str = request.stream.read()
        xml = ET.fromstring(xml_str)
        toUserName = xml.find('ToUserName').text
        fromUserName = xml.find('FromUserName').text
        createTime = xml.find('CreateTime').text
        msgType = xml.find('MsgType').text

        if msgType != 'text':
            reply = '''
            <xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[%s]]></MsgType>
                         <Content><![CDATA[%s]]></Content>
              </xml>
                  '''  % (
                          fromUserName,
                          toUserName,
                          createTime,
                          'text',
                          'Unknown Format, Please check out'
                          )
            return reply

        content = xml.find('Content').text
        msgId = xml.find('MsgId').text
        ###
        if u'笑话' in content or 'joke' in content:
            url = url2 % str(randint(0,35))
            print '\nurl = %s\n' %url
            r = requests.get(url)
            tree = etree.HTML(r.text)
            contentlist = tree.xpath('//div[contains(@id, "qiushi_tag_")]')
            jokes = []

            for i in contentlist:
                content = i.xpath('div[@class="content"]/text()')
                contentstring = ''.join(content)
                contentstring = contentstring.strip('\n')
                jokes.append(contentstring)

            joke = jokes[randint(0,len(jokes))]
            reply = '''
            <xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[%s]]></MsgType>
                         <Content><![CDATA[%s]]></Content>
              </xml>
                  '''  % (
                          fromUserName,
                          toUserName,
                          createTime,
                          msgType,
                          joke 
                          )
            return reply
            
        ###
        else:
            print('type(content)=',type(content))
            if type(content).__name__ == "unicode":
                print(content)
                content = content[::-1]
                content = content.encode('UTF-8')
            elif type(content).__name__ == "str":
                print(type(content).__name__)
                content = content.decode('utf-8')
                content = content[::-1]
        
            reply = '''
            <xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[%s]]></MsgType>
                         <Content><![CDATA[%s]]></Content>
              </xml>
                  '''  % (
                          fromUserName,
                          toUserName,
                          createTime,
                          msgType,
                          content 
                          )
            return reply


if __name__=="__main__":
  while True:
    try:
        app.run(host='0.0.0.0',port=8080)
    except Exception,e:
        print e
>>>>>>> 1996b118a67f2c4d91f256bdd54764c558bd953e